package net.sea.commons.util;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 系统运行时动态加载jar包
 * 
 * @author 华成伍
 *
 */
public class JarLoader {
	
	//设置jarloader不能实例化
	private JarLoader(){
	}
	
	/**
	 * 类加载器
	 */
	private static URLClassLoader urlClassLoader;

	/**
	 * 加载jar包
	 * 
	 * @param urls
	 *            URL地址
	 * @throws Exception
	 */
	public static void loadJar(URL... urls) throws Exception {
		urlClassLoader = new URLClassLoader(urls);
	}

	/**
	 * 获取ClassLoader
	 * 
	 * @return 获取类加载器
	 */
	public static ClassLoader getClassLoader() {
		if (urlClassLoader == null) {
			urlClassLoader = new URLClassLoader(null);
		}
		return urlClassLoader;
	}

	/**
	 * 加载jar包
	 * 
	 * @param path
	 *            加载路径
	 * @throws MalformedURLException
	 * @throws Exception
	 */
	public static void loadJar(String path) throws MalformedURLException,
			Exception {
		if (StringUtils.isNotEmpty(path)) {
			File libDir = new File(path);
			if (libDir.isDirectory()) {
				File[] listFiles = libDir.listFiles(new FileFilter() {

					@Override
					public boolean accept(File file) {
						return file.exists() && file.isFile()
								&& file.getName().endsWith(".jar");
					}
				});

				URL[] urls = new URL[listFiles.length];
				for (int i = 0; i < listFiles.length; i++) {
					urls[i] = listFiles[i].toURI().toURL();
				}
				loadJar(urls);
			} else {
				if (libDir.exists()
						&& (libDir.getName().endsWith(".jar") || libDir
								.getName().endsWith(".class"))) {
					loadJar(new File(path).toURI().toURL());
				} else {
					System.out.println("未找到指定文件或文件类型不正确。");
				}
			}
		} else {
			System.out.println("[信息] 文件不存在，请检查。");
		}
	}

	public static void main(String[] args) throws MalformedURLException,
			Exception {
		loadJar(System.getProperty("user.dir")
				+ "/lib/jdbc/mysql-connector-java-5.1.20-bin.jar");
		Class.forName("com.mysql.jdbc.Driver");
		System.out.println("========================");

	}
}
